﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DynamicIpTool.Service
{
    public partial class ClientForm : Form
    {
        System.Net.WebClient http = new System.Net.WebClient();
        public ClientForm()
        {
            InitializeComponent();
        }
        protected void TryStop()
        {
            WorkerTimer.Stop();
        }

        private void startToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TryStop();
            WorkerTimer.Interval = Appsettings.Default.QueryInterValSec * 1000;
            WorkerTimer.Start();
            startToolStripMenuItem.Checked = true;
            stopToolStripMenuItem.Checked = false;
            DoUpdateAction();
        }

        private void stopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TryStop();
            startToolStripMenuItem.Checked = false;
            stopToolStripMenuItem.Checked = true;
        }

        private void forceUpdateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DoUpdateAction();
        }
        public void DoUpdateAction()
        {
            try
            {
                var qp = Appsettings.Default.QueryUrl;
                foreach (var arg in Appsettings.Default.QueryKeys.Split(','))
                {
                    if(string.IsNullOrEmpty(arg))continue;
                    try
                    {
                        var q = string.Format(qp, arg);
                        Log(q);
                        var r = http.DownloadString(q);
                        Log(r);
                        UpdateHostFile(arg, r);
                        Log("Done.");
                    }
                    catch (Exception ex)
                    {
                        Log(ex.Message,2);
                    }
                }

            }
            catch (Exception ex)
            {
                Log(ex.Message,2);
            }
        }

        private void UpdateHostFile(string arg, string r)
        {
            if (string.IsNullOrEmpty(r) || r.StartsWith("ERROR"))
            {
                return;
            }
            //arg = arg.Substring("DIP_".Length);

            //System.IO.File.OpenWrite();
            var hfn = Environment.ExpandEnvironmentVariables(Appsettings.Default.HostFilePath);
            var lines = System.IO.File.ReadAllLines(hfn);

            for (int i = 0; i < lines.Length; i++)
            {
                var l = lines[i];
                if (!l.StartsWith("#") && l.EndsWith(arg, StringComparison.CurrentCultureIgnoreCase))
                {
                    if (l.StartsWith(r))
                    {
                        Log("Not change.");
                        return;
                    }
                    else
                    {
                        lines[i] = string.Format("{0}\t\t{1}", r, arg);
                        System.IO.File.WriteAllLines(hfn, lines);
                        Log("Host ip updated",2);
                        return;
                    }
                }
            }
            System.IO.File.AppendAllText(hfn, string.Format("\r\n{0}\t\t{1}\r\n", r, arg));
            Log("Host ip append", 2);
        }
        void Log(string s, int level = 0)
        {
            textBox1.AppendText(string.Format("[{0:MM-dd HH:mm:ss.fff}]\t{1}\r\n", DateTime.Now, s));
            if (level > 1)
            {
                notifyIcon1.ShowBalloonTip(1000, string.Empty, s, ToolTipIcon.Warning);
            }
        }

        private void WorkerTimer_Tick(object sender, EventArgs e)
        {
            DoUpdateAction();
        }

        private void clearLogToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
        }

        private void quitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Mail to kevin_geng@163.com to contact me.");
        }

        private void showToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Visible = !this.Visible;
            showToolStripMenuItem.Text = (this.Visible ? "Hide" : "Show") + " window";
        }

        private void quitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = !this.Visible;
            showToolStripMenuItem.Text = (this.Visible ? "Hide" : "Show") + " window";

        }
    }
}
